﻿Imports System.Runtime.CompilerServices
Imports System.Text
Imports System.Security.Cryptography

''' <summary>
''' JOS工具模块
''' </summary>
Public Module JosUtils

    ''' <summary>
    ''' 给JOS请求签名。
    ''' </summary>
    ''' <param name="parameters">所有字符型的JOS请求参数</param>
    ''' <param name="secret">签名密钥</param>
    ''' <param name="qhs">是否前后都加密钥进行签名</param>
    ''' <returns>签名</returns>
    <Extension()>
    Public Function SignJosRequest(ByVal parameters As IDictionary(Of String, String), ByVal secret As String, Optional ByVal qhs As Boolean = False) As String
        ' 第一步：把字典按Key的字母顺序排序
        Dim sortedParams As IDictionary(Of String, String) = New SortedDictionary(Of String, String)(parameters)
        Dim dem As IEnumerator(Of KeyValuePair(Of String, String)) = sortedParams.GetEnumerator()

        ' 第二步：把所有参数名和参数值串在一起
        Dim query As New StringBuilder(secret)
        While dem.MoveNext()
            Dim key As String = dem.Current.Key
            Dim value As String = dem.Current.Value
            If Not String.IsNullOrEmpty(key) AndAlso Not String.IsNullOrEmpty(value) Then
                query.Append(key).Append(value)
            End If
        End While
        If qhs Then
            query.Append(secret)
        End If

        ' 第三步：使用MD5加密
        Dim _md5 As MD5 = MD5.Create()
        Dim bytes As Byte() = _md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()))

        ' 第四步：把二进制转化为大写的十六进制
        Dim result As New StringBuilder()
        For i As Integer = 0 To bytes.Length - 1
            Dim hex As String = bytes(i).ToString("X")
            If hex.Length = 1 Then
                result.Append("0")
            End If
            result.Append(hex)
        Next

        Return result.ToString()
    End Function







End Module